import React, {Component} from 'react';
import { Input, Button, Icon, Table, Popconfirm, message, Form, Modal } from "antd";
import { getCategoryList, addCategory, updateCategory, delCategory } from "../../service/category";
export default class Category extends Component{
  render() {
    console.log('触发次数')
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name'
      },
      {
        title: '操作',
        render: (text, record, index) => {
          return (
            <Button.Group>
              <Button type="primary" onClick={() => this.editAction(record)}>修改</Button>
              <Popconfirm
                title="是否确认删除该分类?"
                onConfirm={() => this.removeItem(record)}>
                <Button type="danger">删除</Button>
              </Popconfirm>
              
            </Button.Group>
          );
        }
      },
    ];

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({selectedRows})
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };

    return (
      <div style={{padding: 15}}>
        <Input.Search 
          placeholder="请输入搜索内容" 
          onSearch={keyword => this.setState({keyword}, this.getList)} 
          enterButton />
        <Button.Group style={{marginTop: 10, marginBottom: 20}}>
          <Button type="primary" onClick={this.create}>
            <Icon type="plus" />
            新增
          </Button>
          <Button type="danger" onClick={() => this.removeItem()}>
            <Icon type="delete" />
            批量删除
          </Button>
        </Button.Group>
        <Table 
          pagination={this.state.pagination} 
          dataSource={this.state.items} 
          columns={columns} 
          rowSelection={rowSelection}/>

        <Modal
          title={this.state.title}
          visible={this.state.editVisible}
          onCancel={this.editCancel}
          onOk={this.editOk}
          destroyOnClose  // 关闭的时候销毁，避免回显
        >
          {/* 取子组件输入框里面的数据
            一般情况下用ref，但是 这个组件是包装过的所以要用
            wrappedComponentRef 来取
          */}
          <WrapedEditModal 
            wrappedComponentRef={inst => this.editfrom = inst}
            editItem={this.state.editItem}
            isCreate={this.state.isCreate}
          />
        </Modal>
      </div>
    );
  }

  state = {
    items: [],
    selectedRows: [],
    keyword: '',
    editItem: null,
    isCreate: true,
    title: '',
    editVisible: false,
    pagination: {current: 1, pageSize: 5}
  }

  create = () => {
    this.setState({
      title: '添加分类',
      isCreate: true,
      editVisible: true
    })
  }
  // 关闭模态框
  editCancel = () => {
    this.setState({editVisible: false})

  }

  // 点击模态框 确定
  editOk = () => {
    let category = this.editfrom.props.form.getFieldsValue();
    console.log('获取的数据', category)
    let actionFn = this.state.isCreate ? addCategory: updateCategory
    actionFn(category).then(res => {
      if(res.code === 0){
        message.success(res.data)
        this.getList()
        this.setState({editVisible: false})
      }else{
        message.error(res.error);
      }
    })
  }

  // 点击 编辑
  editAction = (item) => {
    console.log(item)
    this.setState({title: '更新分类',editItem: item, editVisible: true, isCreate: false})
  }

  removeItem = (item) => {
    let params = {}
    if (!item) {
      if (!this.state.selectedRows.length) {
        return message.error('请选择要删除的行')
      }
      params.ids = this.state.selectedRows.reduce((pre, cur) => `${pre._id},${cur._id}`).split(',')
      params.id = params.ids[0];
    }else{
      params.id = item._id;
    }
    if (!params.id) {
      return
    }
    delCategory(params).then(res => {
      if(res.code === 0){
        message.success(res.data)
        this.setState({pagination: {...this.state.pagination, current: 1}}, this.getList)
      }else{
        message.error(res.error);
      }
    })
  }

  componentDidMount() {
    this.getList();
  }
  // 
  pageChange = (current) => {
    this.setState({
      pagination: {...this.state.pagination, current}
    }, this.getList);

    // this.setState  第二个参数是异步设置state后的 回调
    // 此处指 设置完state后重新请求列表
  }

  // 搜索
  search = () => {

  }

  getList = () => {
    const {current: pageNum, pageSize} = this.state.pagination;

    getCategoryList({pageNum, pageSize, keyword: this.state.keyword}).then(res => {
      if (res.code == 0) {
        const {pageNum: current, pageSize, total, items} = res.data;
        let newItems = items.map(v => (v.key = v._id, v))
        this.setState({
          items: newItems,
          pagination: {
            current, // 当前页
            pageSize, //每页的条数
            total, // 总条数
            showTotal: val => `总计${val}条`,
            onChange: this.pageChange
          }
        })
      }
    })
  }
}



class EditModal extends Component {
  render() {
    const {getFieldDecorator} = this.props.form;
    return (
      <Form>
        <Form.Item>
          {
            getFieldDecorator('name', {
              initialValue: !this.props.isCreate? this.props.editItem.name: '',
              rules: [{required: true, message: '请输入分类名称'}]
            })(<Input placeholder="请输入分类名称" />)
          }
        </Form.Item>
        {
          !this.props.isCreate && (
            <Form.Item>
              {
                getFieldDecorator('id', {
                  initialValue: this.props.editItem._id,
                })(<Input type="hidden" />)
              }
            </Form.Item>
          )
        }
      </Form>
    )
  }
}
// 使用时用 WrapedEditModal， 传给WrapedEditModal的参数也会 传给EditModal
const WrapedEditModal = Form.create()(EditModal)
